<style scoped>
.system-product-item {
  padding-bottom: 60px;
}
.system-product-item .header {
  min-height: 36px;
}
.system-product-item .header .border {
  width: 100%;
  height: 1px;
  border-bottom: 2px solid #e5e5e5;
  margin-top: 12px;
  margin-bottom: 24px;
}
.system-product-item /deep/ .el-form textarea[name="editorValue"]{
  display: none;
}
.footfixed {
  position: fixed;
  z-index: 1000;
  bottom: 0;
  left: 220px;
  right: 0;
  background: #fff;
  padding: 15px 20px;
  border-top: 1px solid #eee;
  margin-bottom: 0 !important;
  text-align: right;
}
</style>
<!--  -->
<template>
  <div class="system-product-item" v-loading="globalLoading">
    <!-- <div class="header">
      <el-row type="flex" justify="end">
        <el-button type="warning" size="small" v-if="system && system.systemType && system.systemType.id === 3"
          @click="categoryTreeShow">分类级别树形结构</el-button>
        <el-button type="warning" size="small" v-if="system && system.systemType && system.systemType.id === 4"
          @click="slugTreeShow">短标题级别树形结构</el-button>
        <el-button type="primary" @click="onSubmit" size="small">保存</el-button>
        <el-button type="success" @click="onSubmitAndGoSystemList" size="small">保存并返回系统列表</el-button>
        <el-button size="small" @click="goSystemList">返回系统列表</el-button>
      </el-row>
      <div class="border"></div>
    </div> -->
    <el-form ref="productForm" :model="product" label-width="130px" :rules="rules" v-loading="formLoading">
      <SystemProductItemForm ref="systemProductItemForm" :categories="categories" :sluges="sluges" :system="system"
        :product="product" :labelContent="labelContent" :globalLoading="globalLoading"
        :resetImageListFace="resetImageListFace" :resetImageListInfo="resetImageListInfo"
        :resetLabelContent="resetLabelContent" :resetFileList="resetFileList" />

      <el-form-item class="footfixed">
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button type="success" @click="onSubmitAndGoSystemList">保存并返回系统列表</el-button>
        <el-button @click="goSystemList">返回系统列表</el-button>
      </el-form-item>
    </el-form>
    <!-- 分类级别树形结构显示 -->
    <!-- <TreeDialog :data="categoryTreeDialog" ref="categoryTreeDialog" title="分类级别树形结构显示" /> -->
  </div>
</template>

<script>

import SystemProductItemForm from '@/components/main/user/system/product/item/SystemProductItemForm.vue'
import TreeDialog from '@/components/common/dialog/TreeDialog.vue'
import * as functions from '@/core/functions.js'
export default {
  created () {
    let query = this.$route.query
    if (!query || !query.sid || !query.id) {
      this.$message.error('未能获取到正确的数据')
      return
    }
    let systemId = query.sid
    let id = query.id
    // 获取系统信息
    this.$post('/system/info', { id: systemId }).then((resoponse) => {
      if (resoponse && resoponse.id) {
        this.system = resoponse
        this.product.base.systemId = this.product.seo.systemId = this.system.id
        if (this.system.systemType && this.system.systemType.id === 3) {
          // 获取所有的分类信息
          this.$post('/category/table-data-infos-by-system-id', { systemId: systemId }).then((resoponse) => {
            if (resoponse.categories) {
              this.categories = resoponse.categories
            } else {
              this.categories = {}
            }
            if (resoponse.categoryIds && resoponse.categoryIds.length > 0) {
              this.product.categoryIds = resoponse.categoryIds
            }
            this.initComplete.categories = true
          })
        } else if (this.system.systemType && this.system.systemType.id === 4) {
          // 获取短标题信息
          this.initComplete.categories = true
        } else {
          // 不需要获取分类、短标题信息
          this.initComplete.categories = true
        }
        // 获取内容信息
        if (id > 0) {
          // 修改
          this.$post('/system/product/info', { productId: id, systemId: systemId }).then(response => {
            if (response && response.sproduct && response.sproduct.id) {
              this.product = initProduct(response, this)
              this.labelContent = initLabelContent(response.listLabelContent)
            } else {
              console.error(response)
            }
            this.initComplete.data = true
          })
        } else {
          this.$post('/url/item-custom-link-path-one-group-by-system-id', {systemId: this.system.id}).then(response => {
            if (response && response.length > 0) {
              this.product.customLink.pathOneGroup = response
            }
          })
          // 新增
          this.initComplete.data = true
        }
      }
      this.initComplete.system = true
    })
  },
  data () {
    return {
      // 全局加载
      globalLoading: true,
      // 表单加载
      formLoading: false,
      // 判断是否加载完成的三个加载项目
      initComplete: {
        categories: false,
        system: false,
        data: false
      },
      // 获取系统的分类信息
      categories: {},
      // 获取文章分级信息
      sluges: {},
      // 当前的系统
      system: {},
      // 表单数据
      product: {
        // 基础信息
        base: {
          id: 0,
          systemId: 0,
          title: '',
          info: '',
          releasedAt: new Date(),
          isShow: true,
          isTop: false,
          orderNum: 1
        },
        // 分类信息
        categoryIds: [],
        // 封面图片
        imageListFace: [],
        // 图片列表
        imageListInfo: [],
        // seo 信息
        seo: { id: 0, systemId: 0, title: '', keywords: '', description: '' },
        fileList: [],
        // 自定义链接信息
        customLink: { id: 0, systemId: 0, status: 1, path: [], lanno: '', pathOneGroup: [], suffix: '.html' }
      },
      // 由于编辑问题将产品内容信息单独拿出来处理
      labelContent: [
        { id: 0, title: '产品详情', content: '', orderNum: 1 }
      ],
      // 验证规则
      rules: {
        'base.title': [
          { required: true, message: '请输入产品名称', trigger: 'blur' },
          { max: 200, message: '长度不能超过200个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    categoryTreeDialog () {
      let result = getCategoryTreeData(this.categories, 0)
      return result
    }
  },
  watch: {
    initComplete: {
      handler (newVal) {
        this.$nextTick(() => {
          if (newVal.categories && newVal.system && newVal.data) {
            // 初始化请求完毕
            this.globalLoading = false
          }
        })
      },
      deep: true
    }
  },
  methods: {
    // 显示分类树形结构
    categoryTreeShow () {
      this.$refs['categoryTreeDialog'].show()
    },
    // 短标题级别树形结构
    slugTreeShow () {
      console.log('slugTreeShow')
    },
    // 保存
    onSubmit (callback) {
      this.$refs['productForm'].validate((valid, vdata) => {
        if (valid) {
          let itemCustomLinkInfo = this.getCustomLink()
          let itemCustomLink
          if (!itemCustomLinkInfo.bool) {
            return
          } else {
            itemCustomLink = {
              path: itemCustomLinkInfo.path,
              status: itemCustomLinkInfo.status
            }
          }
          let param = {
            base: requestProductBaseParam(this.product),
            categoryIds: requestProductCategoryParam(this.product),
            imageListFace: requestProductImageListFaceParam(this.product),
            imageListInfo: requestProductImageListInfoParam(this.product),
            labelContent: requestProductLabelContentParam(this.labelContent, this),
            seo: requestProductSeoParam(this.product),
            fileListInfo: requestProductFileParam(this.product),
            itemCustomLink: itemCustomLink
          }
          this.formLoading = true
          this.$jpost('/system/product/save', param).then(response => {
            if (response && response.sproduct && response.sproduct.id) {
              if (typeof callback === 'function') {
                callback()
              }
              this.product = initProduct(response, this)
              this.labelContent = initLabelContent(response.listLabelContent)
            } else {
              console.error(response)
            }
            this.formLoading = false
          })
        } else {
          for (let i in vdata) {
            for (let j in vdata[i]) {
              let v = vdata[i][j]
              if (v && v.message) {
                this.$message.error(v.message)
              }
              break
            }
          }
          this.$refs['systemProductItemForm'].gotoFirst()
          return false
        }
      })
    },
    // 保存并返回系统列表
    onSubmitAndGoSystemList () {
      this.onSubmit(() => {
        this.goSystemList()
      })
    },
    // 返回系统列表
    goSystemList () {
      let fullPath = functions.getSystemListPathByItem(this.system)
      if (!fullPath) {
        return
      }

      // 存储系统页面页码，如果从编辑页返回列表页fromItem改为true
      let systbPageCur = JSON.parse(sessionStorage.getItem('systbPageCur' + this.system.id))
      if (systbPageCur) {
        systbPageCur.fromItem = true
        sessionStorage.setItem('systbPageCur' + this.system.id, JSON.stringify(systbPageCur))
      }

      this.$store.dispatch('navAppendAndClose', { path: fullPath, close: this.$route.fullPath })
    },
    // 重新设置封面图片的列表
    resetImageListFace (imageList) {
      this.product.imageListFace = imageList
    },
    // 重新设置产品图片列表
    resetImageListInfo (imageList) {
      this.product.imageListInfo = imageList
    },
    // 修改 labelContent
    resetLabelContent (labelContent) {
      this.labelContent = labelContent
    },
    // 通过 index 获取产品内容信息中的富文本编辑内容
    getLabelContent (index) {
      return this.$refs['systemProductItemForm'].getLabelContent(index)
    },
    // 重新设置文件列表
    resetFileList (fileList) {
      this.product.fileList = fileList
    },
    // 获取产品自定义链接数据
    getCustomLink () {
      return this.$refs['systemProductItemForm'].getCustomLink()
    }
  },
  components: {
    SystemProductItemForm,
    TreeDialog
  }
}

function initLabelContent (listLabelContent) {
  if (!listLabelContent || listLabelContent.length < 1) {
    return [
      { id: 0, title: '产品详情', content: '', orderNum: 1 }
    ]
  }
  let labelContent = listLabelContent.map((element, index) => {
    return { id: element.id, title: element.title ? element.title : '', content: element.content ? element.content : '', orderNum: element.orderNum ? element.orderNum : (index + 1) }
  })
  return labelContent
}

function initProduct (product, vm) {
  let sproduct = product.sproduct
  let listCategoryQuote = product.listCategoryQuote
  let listImageListFace = product.listImageListFace
  let listImageListInfo = product.listImageListInfo
  let sseoItem = product.sseoItem
  let listFileListInfo = product.listFileListInfo

  let base = {
    id: sproduct.id,
    systemId: sproduct.systemId,
    title: sproduct.title,
    priceString: sproduct.priceString,
    info: sproduct.info,
    releasedAt: sproduct.releasedAt,
    isShow: sproduct.isShow > 0,
    isTop: sproduct.isTop > 0,
    orderNum: sproduct.orderNum
  }

  let categoryIds = []
  if (listCategoryQuote && listCategoryQuote.length > 0) {
    categoryIds = listCategoryQuote.map(element => {
      return element.scategoriesQuote.categoryId
    })
  }

  let imageListFace = []
  if (listImageListFace && listImageListFace.length > 0) {
    imageListFace = listImageListFace.map(element => {
      let config
      if (element.srepertoryQuote.config) {
        config = JSON.parse(element.srepertoryQuote.config)
      }
      let title = config && config.title ? config.title : element.hrepertory.originalFilename
      let alt = config && config.alt ? config.alt : element.hrepertory.originalFilename
      return {
        id: element.hrepertory.id,
        src: functions.getRepertoryImageSrcByHostRepertory(element.hrepertory),
        title: title,
        alt: alt
      }
    })
  }

  let imageListInfo = []
  if (listImageListInfo && listImageListInfo.length > 0) {
    imageListInfo = listImageListInfo.map(element => {
      let config
      if (element.srepertoryQuote.config) {
        config = JSON.parse(element.srepertoryQuote.config)
      }
      let title = config && config.title ? config.title : element.hrepertory.originalFilename
      let alt = config && config.alt ? config.alt : element.hrepertory.originalFilename
      return {
        id: element.hrepertory.id,
        src: functions.getRepertoryImageSrcByHostRepertory(element.hrepertory),
        title: title,
        alt: alt
      }
    })
  }

  let seo = { id: 0, systemId: sproduct.systemId, title: '', keywords: '', description: '' }
  if (sseoItem && sseoItem.id) {
    seo = {
      id: sseoItem.id,
      systemId: sseoItem.systemId,
      title: sseoItem.title,
      keywords: sseoItem.keywords,
      description: sseoItem.description
    }
  }

  let fileList = []
  if (listFileListInfo && listFileListInfo.length > 0) {
    fileList = listFileListInfo.map(item => {
      return {
        id: item.hrepertory.id,
        originalFilename: item.hrepertory.originalFilename,
        suffix: item.hrepertory.suffix
      }
    })
  }

  return {
    // 基础信息
    base: base,
    // 分类信息
    categoryIds: categoryIds,
    // 封面图片
    imageListFace: imageListFace,
    // 图片列表
    imageListInfo: imageListInfo,
    // seo 信息
    seo: seo,
    // 文件列表
    fileList: fileList,
    // 自定义链接
    customLink: product.customLink
  }
}

// 提交数据时的基础信息
function requestProductBaseParam (product) {
  let base = JSON.parse(JSON.stringify(product.base))
  base.isShow = base.isShow ? 1 : 0
  base.isTop = base.isTop ? 1 : 0
  base.orderNum = parseInt(base.orderNum)
  return base
}

// 提交数据时的分类信息
function requestProductCategoryParam (product) {
  let categoryIds = JSON.parse(JSON.stringify(product.categoryIds))
  return categoryIds
}

// 提交数据时的封面图片数据 imageListFace
function requestProductImageListFaceParam (product) {
  let imageListFace = JSON.parse(JSON.stringify(product.imageListFace))
  return imageListFace
}

// 提交数据时的封面图片数据 imageListInfo
function requestProductImageListInfoParam (product) {
  let imageListInfo = JSON.parse(JSON.stringify(product.imageListInfo))
  return imageListInfo
}

// 提交数据时的产品内容信息数据 labelContent
function requestProductLabelContentParam (labelContents, vm) {
  let labelContent = JSON.parse(JSON.stringify(labelContents))
  labelContent.forEach((element, index) => {
    element.content = vm.getLabelContent(index)
  })
  return labelContent
}

// 提交数据时的产品SEO信息数据 seo
function requestProductSeoParam (product) {
  let seo = JSON.parse(JSON.stringify(product.seo))
  return seo
}

// 提交数据时的产品文件信息数据
function requestProductFileParam (product) {
  let files = product.fileList.map(item => {
    return {
      id: item.id
    }
  })
  return files
}

// 构建分类树形结构数据
function getCategoryTreeData (data, key) {
  if (data.length < 1) {
    return []
  }
  let result = []
  for (let i in data[key]) {
    let item = data[key][i]
    let children
    if (data.hasOwnProperty(item.id)) {
      children = getCategoryTreeData(data, item.id)
    }
    let element = {}
    element.label = item.name
    if (children) {
      element.children = children
    }
    result.push(element)
  }
  return result
}

</script>
